package cn.jlearn.proxy.server.handler.bs;

import cn.jlearn.proxy.common.body.ClientConnectSuccessBody;
import cn.jlearn.proxy.common.enums.MsgTypeEnum;
import cn.jlearn.proxy.common.handler.AbstractBsHandler;
import cn.jlearn.proxy.common.packet.BsPacket;
import cn.jlearn.proxy.server.container.ProxyServer;
import cn.jlearn.proxy.server.utils.RedissonUtil;
import com.alibaba.fastjson.JSON;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;

/**
 * @author qianyingchao
 * @version 1.0
 * @date 2021/5/18 10:15 下午
 */
public class ClientConnectSuccessReqHandler extends AbstractBsHandler<ClientConnectSuccessBody> {

    @Override
    public Class<ClientConnectSuccessBody> bodyClass() {
        return ClientConnectSuccessBody.class;
    }

    @Override
    public void handler(BsPacket packet, ClientConnectSuccessBody bsBody, ChannelContext channelContext) throws Exception {
        RedissonUtil.getInstance().set(bsBody.getHost(), bsBody.getToken());

        channelContext.set("host", bsBody.getHost());
        channelContext.set("token", bsBody.getToken());

        Tio.bindBsId(channelContext, bsBody.getToken());

        ClientConnectSuccessBody body = new ClientConnectSuccessBody(bsBody.getToken(), bsBody.getHost(), bsBody.getChannelId());
        BsPacket bsPacket = new BsPacket(MsgTypeEnum.TCP_CLIENT_CONNECT_SUCCESS_RES.getCode(), JSON.toJSONBytes(body));

        Tio.sendToBsId(ProxyServer.serverTioConfig, bsBody.getToken(), bsPacket);

    }

}
